package Example1;

import com.sun.xml.internal.ws.api.ha.StickyFeature;
import jdk.nashorn.internal.runtime.ScriptRuntime;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Example4 {
    private static void insertStudent(String sql) throws SQLException {
        Connection connection = DBUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(sql);
        int ret = statement.executeUpdate();
        if (ret != 1){
            System.out.println("数据新增失败!");
        }else{
            System.out.println("数据新增成功!");
        }
        DBUtil.close(connection,statement,null);
    }
    private static void deleteStudent(String sql) throws SQLException {
        Connection connection = DBUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(sql);
        int ret = statement.executeUpdate();
        if (ret != 1){
            System.out.println("数据删除失败!");
        }else{
            System.out.println("数据删除成功!");
        }
        DBUtil.close(connection,statement,null);
    }
    private static void updateStudent(String sql) throws SQLException {
        Connection connection = DBUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(sql);
        int ret = statement.executeUpdate();
        if (ret >= 1){
            System.out.println("数据修改失败!");
        }else{
            System.out.println("数据修改成功!");
        }
        DBUtil.close(connection,statement,null);
    }
    private static void selectStudent(String sql) throws SQLException {
        Connection connection = DBUtil.getConnection();
        List<Student> students = new ArrayList<>();
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        while(resultSet.next()){
            Student student = new Student();
            student.setId(resultSet.getInt("id"));
            student.setName(resultSet.getString("name"));
            students.add(student);
        }
        DBUtil.close(connection,statement,resultSet);
        for (Student student : students){
            System.out.println(student.toString());
        }
        System.out.println("查询完成!");
    }
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入新增的数据: ");
        String sql1 = scanner.nextLine();
        insertStudent(sql1);
        System.out.print("请输入修改的数据: ");
        String sql2 = scanner.nextLine();
        updateStudent(sql2);
        System.out.print("请输入查询的数据: ");
        String sql3 = scanner.nextLine();
        selectStudent(sql3);
        System.out.print("请输入删除的数据: ");
        String sql4 = scanner.nextLine();
        updateStudent(sql4);
    }
}
